<template>
  <div class="page-store-billing">
    <div class="total-amount">
      <div class="item">
        <div class="pay-name">
          {{ $t('shop.availableStoreBalance') }}
          <el-tooltip
            effect="dark"
            placement="right"
          >
            <template #content>
              <div style="max-width:500px">
                {{ $t('shopWallet.availableStoreBalancesTip') }}
              </div>
            </template>

            <el-icon>
              <QuestionFilled />
            </el-icon>
          </el-tooltip>
        </div>
        <div class="pay-amount">
          {{ details.settledAmount }}
        </div>
        <!-- <div class="pay-percent">{{ details.wechatPercent | percent }}%</div> -->
      </div>
      <div class="item">
        <div class="pay-name">
          {{ $t('shop.pendingSettlement') }}
          <el-tooltip
            effect="dark"
            placement="right"
          >
            <template #content>
              <div style="max-width:500px">
                {{ $t('shop.pendingSettlementTip') }}
              </div>
            </template>
            <el-icon>
              <QuestionFilled />
            </el-icon>
          </el-tooltip>
        </div>
        <div class="pay-amount">
          {{ details.unsettledAmount }}
        </div>
        <!-- <div class="pay-percent">{{ details.alipayPercent | percent }}%</div> -->
      </div>
      <div class="item">
        <div class="pay-name">
          {{ $t('shopWallet.freezeBalances') }}
          <el-tooltip
            effect="dark"
            placement="right"
          >
            <template #content>
              <div style="max-width:500px">
                {{ $t('shop.unusableBalanceYuanTip') }}
              </div>
            </template>
            <el-icon>
              <QuestionFilled />
            </el-icon>
          </el-tooltip>
        </div>
        <div class="pay-amount">
          {{ details.freezeAmount }}
        </div>
        <!-- <div class="pay-percent">{{ details.balancePercent | percent }}%</div> -->
      </div>
      <div class="item">
        <div class="pay-name">
          {{ $t('shop.totalSettlementAmount') }}
          <el-tooltip
            effect="dark"
            placement="right"
          >
            <template #content>
              <div style="max-width:500px">
                {{ $t("shop.totalSettlementAmountTip2") }}
              </div>
            </template>
            <el-icon>
              <QuestionFilled />
            </el-icon>
          </el-tooltip>
        </div>
        <div class="pay-amount">
          {{ details.totalSettledAmount }}
        </div>
        <!-- <div class="pay-percent">{{ details.balancePercent | percent }}%</div> -->
      </div>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form
        ref="searchFormRef"
        :inline="true"
        :model="searchForm"
        @submit.prevent
      >
        <div class="input-row">
          <el-form-item :label="$t('coupon.shopName') + ':'">
            <el-input
              v-model="searchForm.shopName"
              style="min-width: 240px;"
              clearable
              :placeholder="$t('coupon.pleEntShopName')"
            />
          </el-form-item>
          <el-form-item :label="$t('formData.timeLimit') + ':'">
            <el-select
              v-model="datePickerType"
              class="date-picker-type"
              @change="setdatePickerType(datePickerType)"
            >
              <el-option
                v-for="item in datePickerTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-date-picker
              v-model="dateRangeParam"
              :type="datePickerType"
              clearable
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm:ss"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0),
                              new Date(2000, 2, 1, 23, 59, 59)]"
              :range-separator="$t('date.tip')"
              :start-placeholder="$t('date.start')"
              :end-placeholder="$t('date.end')"
            />
          </el-form-item>
          <el-form-item>
            <div
              class="default-btn primary-btn"
              @click="searchChange"
            >
              {{ $t('order.query') }}
            </div>
            <div
              class="default-btn"
              @click="resetSearchForm"
            >
              {{ $t('product.reset') }}
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>

    <div class="table-box">
      <el-tabs
        v-model="activeName"
        @tab-click="handleClick"
      >
        <el-tab-pane
          :label="$t('shopWallet.transactionHistory')"
          name="trade"
        >
          <recording
            ref="tradeRef"
            :active-name="activeName"
            @selection-change="selectionChange"
          />
        </el-tab-pane>
        <!-- <el-tab-pane :label="$t('shopWallet.withdrawalRecords')" name="withdrawals">
          <recording :active-name="activeName" ref="withdrawals" />
        </el-tab-pane> -->
      </el-tabs>
      <div class="export-btn">
        <el-button
          v-if="isAuth('shop:wallet:excel')"
          :icon="Download"
          @click="exportFrom()"
        >
          {{ $t('order.export') }}
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import recording from './components/recording.vue'
import { Download } from '@element-plus/icons-vue'

import { ElLoading, ElMessage } from 'element-plus'
import { onMounted, reactive } from 'vue'
import { isAuth } from '@/utils'

const Data = reactive({
  activeName: 'trade', // 对账类型 0支出 1 收入
  datePickerType: 'daterange', // 日期筛选类型
  shopName: '',
  dateRangeParam: [],
  searchForm: {
    startTime: '',
    endTime: '',
    shopName: '',
    size: 10,
    current: 1
  },
  tableData: [],
  details: {},
  datePickerTypeOptions: [
    {
      label: $t('date.daterange'),
      value: 'daterange'
    },
    {
      label: $t('date.monthrange'),
      value: 'monthrange'
    }
  ]
})

const { activeName, datePickerType, dateRangeParam, searchForm, details, datePickerTypeOptions } = toRefs(Data)

onMounted(() => {
  getData()
  getDataDetail()
})

const handleClick = () => {
  getData()
}

const tradeRef = ref()
const getData = () => {
  tradeRef.value.getDataDetail(JSON.parse(JSON.stringify(Data.searchForm)))
}

const getDataDetail = () => {
  Data.details = {
    freezeAmount: '-',
    settledAmount: '-',
    totalSettledAmount: '-',
    unsettledAmount: '-'
  }
  http({
    url: http.adornUrl('/shop/shopWallet/getAllShopWallet'),
    method: 'get',
    params: Data.searchForm
  }).then(({ data }) => {
    Data.details.freezeAmount = data && data.freezeAmount !== null ? data.freezeAmount : '-'
    Data.details.settledAmount = data && data.settledAmount !== null ? data.settledAmount : '-'
    Data.details.totalSettledAmount = data && data.totalSettledAmount !== null ? data.totalSettledAmount : '-'
    Data.details.unsettledAmount = data && data.unsettledAmount !== null ? data.unsettledAmount : '-'
  })
}

const setdatePickerType = (val) => {
  Data.datePickerType = val
}

const selectionChange = (list) => {
  Data.shopIdList = list
}

// 条件查询
const searchChange = () => {
  Data.searchForm.startTime = Data.dateRangeParam ? Data.dateRangeParam[0] : ''
  Data.searchForm.endTime = Data.dateRangeParam ? Data.dateRangeParam[1] : ''
  getDataDetail()
  getData()
}

/**
       * 重置表单
       * @param {String} formName 表单名称
       */
const resetSearchForm = () => {
  Data.searchForm.shopName = ''
  Data.dateRangeParam = ''
}

const exportFrom = () => {
  Data.searchForm.startTime = Data.dateRangeParam ? Data.dateRangeParam[0] : ''
  Data.searchForm.endTime = Data.dateRangeParam ? Data.dateRangeParam[1] : ''
  if (!Data.dateRangeParam) {
    ElMessage.warning($t('tip.select') + $t('formData.timeLimit'))
    return
  }
  const params = { ...Data.searchForm }
  params.shopIds = Data.shopIdList
  const loading = ElLoading.service({
    lock: true,
    target: '.table-box',
    customClass: 'export-load',
    background: 'transparent',
    text: $t('shop.exportIng')
  })
  http({
    url: http.adornUrl('/shop/shopWallet/getShopWalletLogForm'),
    method: 'get',
    params: http.adornParams(params),
    responseType: 'blob'
  }).then(({ data }) => {
    loading.close()
    const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
    const fileName = $t('finaManage.storeBilling') + '.xlsx'

    const elink = document.createElement('a')
    if ('download' in elink) { // 非IE下载
      elink.download = fileName
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href) // 释放URL 对象
      document.body.removeChild(elink)
    } else { // IE10+下载
      navigator.msSaveBlob(blob, fileName)
    }
  }).catch((e) => {
    loading.close()
  })
}
</script>

<style lang="scss" scoped>
.page-store-billing {
  .total-amount {
    background: #f7f8fa;
    padding: 15px 40px;
    flex-wrap: wrap;
    width: 100%;
    display: flex;
    flex-direction: row;

    .item {
      // flex: 1;
      font-size: 14px;
      width: 25%;

      .pay-name {
        color: #666;
        margin-bottom: 8px;
      }

      .pay-amount {
        color: #333;
        font-size: 26px;
        font-weight: bold;
        margin-bottom: 8px;
      }
    }
  }

  .table-box {
    position: relative;

    .export-btn {
      position: absolute;
      right: 0;
      top: -5px;
    }
  }

  // 搜索栏
  .search-bar {
    margin-top: 20px;
    padding-bottom: 25px;

    .input-row {

      .default-btn {
        margin-left: 20px;
      }
    }
  }

  .date-picker-type {
    width: 120px !important;
  }

  :deep(.date-picker-type .el-input--suffix) {
    width: 120px !important;
  }

  :deep(.el-range-separator) {
    width: 18px;
  }

  :deep(.el-date-editor--daterange) {
    width: 300px !important;
  }

  :deep(.export-load) {
    top: -50% !important;
  }

  :deep(.search-bar .input-row .el-form-item__content .el-input) {
    width: 100%;
  }
}
</style>
